package com.huixi.microspur.web.controller.appeal;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.huixi.microspur.commons.base.BaseController;
import com.huixi.microspur.commons.enums.ErrorCodeEnum;
import com.huixi.microspur.commons.page.PageData;
import com.huixi.microspur.commons.util.wrapper.WrapMapper;
import com.huixi.microspur.commons.util.wrapper.Wrapper;
import com.huixi.microspur.web.pojo.dto.appeal.UpdateAppealDTO;
import com.huixi.microspur.web.pojo.dto.appeal.WjAppealByUserDTO;
import com.huixi.microspur.web.pojo.dto.appeal.WjAppealDTO;
import com.huixi.microspur.web.pojo.entity.appeal.WjAppealAddress;
import com.huixi.microspur.web.pojo.vo.appeal.QueryAppealVO;
import com.huixi.microspur.web.pojo.dto.appeal.WjAppealPageDTO;
import com.huixi.microspur.web.pojo.entity.appeal.WjAppeal;
import com.huixi.microspur.web.pojo.entity.appeal.WjAppealMaterial;
import com.huixi.microspur.web.pojo.entity.appeal.WjAppealTag;
import com.huixi.microspur.web.pojo.entity.user.WjUser;
import com.huixi.microspur.web.service.*;
import com.huixi.microspur.web.util.CommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * 诉求表 前端控制器
 * </p>
 *
 * @author xzl
 * @since 2020-01-17
 */
@RestController
@RequestMapping("/wjAppeal")
@Api(tags = "诉求-模块的接口")
public class WjAppealController extends BaseController {

    @Resource
    private WjAppealService wjAppealService;

    @Resource
    private WjAppealMaterialService wjAppealMaterialService;

    @Resource
    private WjAppealTagService wjAppealTagService;

    @Resource
    private WjAppealAddressService wjAppealAddressService;

    @Resource
    private WjAppealEndorseService wjAppealEndorseService;

    @Resource
    private WjUserService wjUserService;

    @Resource
    private WjChatService wjChatService;


    /**
     * 添加 诉求数据
     *
     * @param wjAppealDTO
     * @return com.huixi.microspur.commons.util.wrapper.Wrapper
     * @Author 叶秋
     * @Date 2020/4/13 22:18
     **/
    @PostMapping("/appeal")
    @ApiOperation(value = "添加诉求")

    public Wrapper addAppeal(@RequestBody WjAppealDTO wjAppealDTO) {

        WjAppeal wjAppeal = new WjAppeal();
        BeanUtil.copyProperties(wjAppealDTO, wjAppeal);

        wjAppeal.setUserId(CommonUtil.getNowUserId());

        boolean save = wjAppealService.save(wjAppeal);

        // 保存素材
        if (wjAppealDTO.getMaterialList().length != 0) {

            String[] materialList = wjAppealDTO.getMaterialList();
            for (String s : materialList) {

                String fileType = s.substring(s.lastIndexOf(".") + 1);

                WjAppealMaterial wjAppealMaterial = new WjAppealMaterial()
                        .setAppealId(wjAppeal.getAppealId()).setUrl(s)
                        .setFileType(fileType);

                wjAppealMaterialService.save(wjAppealMaterial);
            }
        }

        // 保存经纬度
        if(StrUtil.isNotBlank(wjAppealDTO.getLatitude()) && StrUtil.isNotBlank(wjAppealDTO.getLongitude())){

            WjAppealAddress wjAppealAddress = new WjAppealAddress()
                    .setAppealId(wjAppeal.getAppealId())
                    .setLatitude(wjAppealDTO.getLatitude())
                    .setLongitude(wjAppealDTO.getLongitude());

            boolean save1 = wjAppealAddressService.save(wjAppealAddress);

        }


        return WrapMapper.ok(save);
    }


    /**
     * 删除诉求
     *
     * @param appealId 诉求id
     * @return com.huixi.microspur.commons.util.wrapper.Wrapper
     * @Author 叶秋
     * @Date 2020/6/18 22:58
     **/
    @DeleteMapping("/appeal/{appealId}")
    @ApiOperation(value = "删除诉求")
    public Wrapper deleteAppeal(@PathVariable String appealId) {

        String nowUserId = CommonUtil.getNowUserId();

        // 先校验改用户有误权限删除这条
        QueryWrapper<WjAppeal> wjAppealQueryWrapper = new QueryWrapper<>();
        wjAppealQueryWrapper.eq("appeal_id", appealId).eq("user_id", nowUserId);
        WjAppeal one = wjAppealService.getOne(wjAppealQueryWrapper);

        if (ObjectUtil.isNull(one)) {
            return WrapMapper.error(ErrorCodeEnum.PRO999990001);
        }

        boolean b = wjAppealService.removeById(appealId);


        return WrapMapper.ok(b);
    }


    /**
     * 修改自己的诉求，需要限制修改次数
     *
     * @param
     * @return com.huixi.microspur.commons.util.wrapper.Wrapper
     * @Author 叶秋
     * @Date 2020/6/30 22:14
     **/
    @PutMapping("/updateAppeal")
    @ApiOperation(value = "修改自己的诉求，需要限制修改次数")
    public Wrapper updateAppeal(@RequestBody UpdateAppealDTO updateAppealDTO) {

        // 限制 标签数量
        int tagLength = 3;
        // 限制修改次数
        int updateCount = 1;

        // 限制标签长度
        if (updateAppealDTO.getTagName().length > tagLength) {
            return WrapMapper.error("标签太多了");
        }


        String nowUserId = CommonUtil.getNowUserId();
        // 判断是否是自己的诉求
        Boolean aBoolean = wjAppealService.judgeAppealIsMe(updateAppealDTO.getAppealId(), nowUserId);
        if (!aBoolean) {
            return WrapMapper.error("这可不是你发布的诉求哦");
        }
        // 是否超过了修改次数
        WjAppeal byId = wjAppealService.getById(updateAppealDTO.getAppealId());
        if (byId.getUpdateCount() >= updateCount) {
            return WrapMapper.error("只能修改" + updateCount + "次哦");
        }


        // 修改诉求
        WjAppeal wjAppeal = new WjAppeal();
        BeanUtil.copyProperties(updateAppealDTO, wjAppeal);

        // 修改素材(把之前的对应关系删除)
        if (updateAppealDTO.getMaterialList().length != 0) {
            wjAppealMaterialService.replaceBeforeMaterial(updateAppealDTO.getAppealId(), updateAppealDTO.getMaterialList());
        }

        // 修改地址
        if (StrUtil.isNotBlank(updateAppealDTO.getLat()) && StrUtil.isNotBlank(updateAppealDTO.getLng())) {
            UpdateWrapper<WjAppealAddress> wjAppealAddressUpdateWrapper = new UpdateWrapper<>();
            wjAppealAddressUpdateWrapper.eq("appeal_id", updateAppealDTO.getAppealId())
                    .set("lat", updateAppealDTO.getLat()).set("lng", updateAppealDTO.getLng());

        }


        return WrapMapper.ok();
    }


    /**
     * 按条件分页查询 诉求
     *
     * @param
     * @Author 叶秋
     * @Date 2020/2/26 21:14
     **/
    @PostMapping("/pageAppeal")
    @ApiOperation(value = "按条件分页查询 诉求")
    public Wrapper listPageAppeal(@RequestBody WjAppealPageDTO wjAppealPageDTO) {

        String nowUserId = CommonUtil.getNowUserId();
        wjAppealPageDTO.setUserId(nowUserId);

        PageData pageData = wjAppealService.listPageAppeal(wjAppealPageDTO);


        return WrapMapper.ok(pageData);
    }


    /**
     * 根据诉求id 查询诉求
     *
     * @param appealId 诉求id
     * @return com.huixi.microspur.commons.util.wrapper.Wrapper
     * @Author 叶秋
     * @Date 2020/6/3 21:24
     **/
    @GetMapping("/appeal/{appealId}")
    @ApiOperation(value = "根据id 查询诉求")
    public Wrapper getByIdAppeal(@Valid @NotNull(message = "诉求id为空") @PathVariable String appealId) {

        QueryAppealVO queryAppealVO = new QueryAppealVO();

        // 根据id查询具体诉求
        WjAppeal byIdAppeal = wjAppealService.getById(appealId);
        // 查询相关的用户信息
        WjUser byIdUser = wjUserService.getById(byIdAppeal.getUserId());
        queryAppealVO.setNickName(byIdUser.getNickName())
                .setHeadPortrait(byIdUser.getHeadPortrait());
        // 查询相关素材
        List<WjAppealMaterial> wjAppealMaterials = wjAppealMaterialService.listByAppealId(byIdAppeal.getAppealId());
        queryAppealVO.setAppealMaterial(wjAppealMaterials);
        // 查询相关标签
        List<WjAppealTag> wjAppealTags = wjAppealTagService.listByAppealTag(appealId);
        queryAppealVO.setAppealTag(wjAppealTags);

        // 诉求
        BeanUtil.copyProperties(byIdAppeal, queryAppealVO);

        return WrapMapper.ok(queryAppealVO);

    }


    /**
     * 分页查询我的所有的诉求（就是查询我的 诉求）
     *
     * @param
     * @return com.huixi.microspur.commons.util.wrapper.Wrapper
     * @Author 叶秋
     * @Date 2020/6/2 21:54
     **/
    @PostMapping("/myAppeal")
    @ApiOperation(value = "根据所给的用户id 分页查询他所有的诉求（就是查询我的 诉求）")
    public Wrapper listByUserIdMyAppeal(@RequestBody WjAppealPageDTO wjAppealPageVO) {

        String nowUserId = CommonUtil.getNowUserId();
        wjAppealPageVO.setUserId(nowUserId);


        PageData pageData = wjAppealService.ListByUserIdMyAppeal(wjAppealPageVO);


        return WrapMapper.ok(pageData);
    }


    /**
     * 根据所给的用户id 分页查询他的诉求
     *
     * @param
     * @return com.huixi.microspur.commons.util.wrapper.Wrapper
     * @Author 叶秋
     * @Date 2020/6/30 21:28
     **/
    @PostMapping("/listByUserIdAppeal")
    @ApiOperation(value = "根据所给的用户id 分页查询他的诉求")
    public Wrapper listByUserIdAppeal(@RequestBody WjAppealByUserDTO wjAppealByUserDTO) {

        if (StrUtil.isEmpty(wjAppealByUserDTO.getUserId())) {
            return WrapMapper.error("被查询的用户id为空");
        }

        WjAppealPageDTO wjAppealPageVO = new WjAppealPageDTO();
        BeanUtil.copyProperties(wjAppealByUserDTO, wjAppealPageVO);

        PageData pageData = wjAppealService.ListByUserIdMyAppeal(wjAppealPageVO);


        return WrapMapper.ok(pageData);
    }


    /**
     * 与发布诉求的人沟通
     *
     * @param
     * @return com.huixi.microspur.commons.util.wrapper.Wrapper
     * @Author 叶秋
     * @Date 2020/7/9 21:24
     **/
    @PostMapping("/communicationAndAppeal")
    @ApiOperation(value = "与发布诉求的人沟通")
    public Wrapper communicationAndAppeal(@Valid @NotNull(message = "诉求id为空") @PathVariable String appealId) {

        String nowUserId = CommonUtil.getNowUserId();

        Boolean aBoolean = wjAppealService.verifyAppealFull(appealId);
        if (aBoolean) {
            return WrapMapper.error("不可与其沟通哦");
        }

        // 创建聊天室
        Boolean appealChat = wjChatService.createAppealChat(appealId, nowUserId);

        return WrapMapper.ok(appealChat);
    }


}

